package com.djmw.mouse.service.account;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.djmw.mouse.entity.AdminUser;
import com.djmw.mouse.repository.AdminUserDao;
import com.djmw.mouse.service.ServiceException;

/**
 * 用户管理类.
 * 
 * @author michael
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class AdminAccountService extends AccountService {

	@Autowired
	private AdminUserDao adminUserDao;

	@Override
	public List<AdminUser> getAllUser() {
		return (List<AdminUser>) adminUserDao.findAll();
	}

	@Override
	public AdminUser getUser(Long id) {
		return adminUserDao.findOne(id);
	}

	@Override
	public AdminUser findUserByLoginName(String loginName) {
		return adminUserDao.findByLoginName(loginName);
	}

	@Transactional(readOnly = false)
	public void registerUser(AdminUser user) {
		entryptPassword(user);
		user.setRoles("admin");
		user.setRegisterDate(dateProvider.getDate());

		adminUserDao.save(user);
	}

	@Transactional(readOnly = false)
	public void updateUser(AdminUser user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		adminUserDao.save(user);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		adminUserDao.delete(id);
	}
}
